package com.ctshk.rpc.guide.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.custom.dto.trip.TripScheduleGuideDTO;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleService;
import com.ctshk.rpc.guide.dto.*;
import com.ctshk.rpc.guide.entity.*;
import com.ctshk.rpc.guide.enums.GroupCollarCertificatesStatus;
import com.ctshk.rpc.guide.enums.GroupDistributionGroupStatus;
import com.ctshk.rpc.guide.enums.GroupDistributionGroupType;
import com.ctshk.rpc.guide.enums.GroupDistributionStatus;
import com.ctshk.rpc.guide.mapper.*;
import com.ctshk.rpc.guide.req.*;
import com.ctshk.rpc.guide.service.IGroupDistributionService;
import com.ctshk.rpc.system.dto.MainDataFieldDataDTO;
import com.ctshk.rpc.system.service.IMainDataFieldDataService;
import com.ctshk.rpc.tour.service.ISeriesTripScheduleService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 团队分配表（派团） 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-02-25
 */
@DubboService
public class GroupDistributionServiceImpl extends ServiceImpl<GroupDistributionMapper, GroupDistribution> implements IGroupDistributionService {

    @DubboReference
    private IMainDataFieldDataService mainDataFieldDataService;
    @DubboReference
    private ICustomizedTripScheduleService customizedTripScheduleService;
    @DubboReference
    private ISeriesTripScheduleService seriesTripScheduleService;
    @Autowired
    private GroupDistributionFullCompanyMapper groupDistributionFullCompanyMapper;
    @Autowired
    private GroupDistributionGiveGroupMapper groupDistributionGiveGroupMapper;
    @Autowired
    private GuideCollarMapper guideCollarMapper;
    @Autowired
    private GuideCollarCertificatesMapper guideCollarCertificatesMapper;
    @Autowired
    private GuideCollarSchedulingMapper guideCollarSchedulingMapper;
    @Autowired
    private GuideCollarSchedulingServiceImpl guideCollarSchedulingService;
    @Autowired
    private TeaPartyMapper teaPartyMapper;

    @Override
    public List<GuideCollarSchedulingDTO> getTask(GuideCollarQueryLeisureReq req) {
        QueryWrapper<GuideCollarScheduling> gcs = getQW(req);
        //得到当前这段时间有任务的人
        List<GuideCollarScheduling> guideCollarSchedulings = guideCollarSchedulingMapper.selectList(gcs);
        List<GuideCollarSchedulingDTO> result = EntityUtil.copyList(guideCollarSchedulings, GuideCollarSchedulingDTO.class);
        return result;
    }

    /**
     * 抽取代码片段
     *
     * @param req
     * @return
     */
    private QueryWrapper<GuideCollarScheduling> getQW(GuideCollarQueryLeisureReq req) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        QueryWrapper<GuideCollarScheduling> gcs = new QueryWrapper<>();
        gcs.lambda().eq(GuideCollarScheduling::getIsDeleted, IsDeletedCode.NO.getCode());
        //当前开始时间是上午
        if (req.getBeginDate().getHour() < 12) {
            //全陪需要跟到团结束
            if (req.getType() == GuideCollarType.NATIONAL_GUIDE.getCode()) {
                gcs.lambda().ge(GuideCollarScheduling::getSchedulingDate, req.getBeginDate().format(dtf))
                        .le(GuideCollarScheduling::getSchedulingDate, req.getEndDate().format(dtf));
            } else {
                //茶会:送团 都是半天的
                gcs.lambda().eq(GuideCollarScheduling::getSchedulingDate, req.getBeginDate().format(dtf))
                        .in(GuideCollarScheduling::getWorkingHours, Arrays.asList(GuideCollarSchedulingWorkHours.FORENOON.getCode(),
                                GuideCollarSchedulingWorkHours.ALL_DAY_LONG.getCode()));//上午有任务或全天有任务的
            }
        } else {
            //下午  全陪需要跟到团结束
            if (req.getType() == GuideCollarType.NATIONAL_GUIDE.getCode()) {
                QueryWrapper<GuideCollarScheduling> clone = gcs.clone();//在时间条件设置之前克隆一个条件是不带上午的
                gcs.lambda().ge(GuideCollarScheduling::getSchedulingDate, req.getBeginDate().format(dtf))
                        .le(GuideCollarScheduling::getSchedulingDate, req.getEndDate().format(dtf));
                //时间额外向后推移一天 然后加上 出发日下午的下半天
                clone.lambda().ge(GuideCollarScheduling::getSchedulingDate, req.getBeginDate().plusDays(1).format(dtf))
                        .le(GuideCollarScheduling::getSchedulingDate, req.getEndDate().format(dtf));
                List<GuideCollarScheduling> a = guideCollarSchedulingMapper.selectList(clone);//得到除开出发日下午到结束的全部任务安排
                //查出发日期上午的人排除(如果上午的人出现在了安排的区域日期中就不排除了)
                // 不需要排除结束的后半天因为结束是整天（如果结束时间是半天的那啊代码又多了一堆）
                QueryWrapper<GuideCollarScheduling> notIns = new QueryWrapper<>();
                notIns.lambda().eq(GuideCollarScheduling::getSchedulingDate, req.getBeginDate().format(dtf))
                        .eq(GuideCollarScheduling::getWorkingHours, GuideCollarSchedulingWorkHours.FORENOON.getCode());//1是上午
                List<GuideCollarScheduling> b = guideCollarSchedulingMapper.selectList(notIns);
                notIns.clear();//清空条件
                notIns.lambda().eq(GuideCollarScheduling::getSchedulingDate, req.getBeginDate().format(dtf))
                        .eq(GuideCollarScheduling::getWorkingHours, GuideCollarSchedulingWorkHours.AFTERNOON.getCode());//2是上午
                List<GuideCollarScheduling> c = guideCollarSchedulingMapper.selectList(notIns);//得到下午的工作安排
                if (b != null && !b.isEmpty() && a != null && !a.isEmpty()) {
                    //合并成团详情出发到结束 这段时间全陪的所有任务安排
                    if (c != null && c.size() > 0) {
                        a.addAll(c);
                    }
                    Set<Long> collecta = a.stream().map(e -> e.getGuideCollarId()).collect(Collectors.toSet());
                    Set<Long> collectb = b.stream().map(e -> e.getGuideCollarId()).collect(Collectors.toSet());
                    //啊这个地方有点烧脑子，后来的大佬自求多福吧。
                    for (Long item : collectb) {
                        if (collecta.contains(item)) {
                            collectb.remove(item);
                        }
                    }
                    if (b != null && !b.isEmpty()) {
                        gcs.lambda().notIn(GuideCollarScheduling::getGuideCollarId, collectb);
                    }
                }
            } else {
                //茶会:送团 都是半天的
                gcs.lambda().eq(GuideCollarScheduling::getSchedulingDate, req.getBeginDate().format(dtf))
                        .in(GuideCollarScheduling::getWorkingHours, Arrays.asList(
                                GuideCollarSchedulingWorkHours.AFTERNOON.getCode(),
                                GuideCollarSchedulingWorkHours.ALL_DAY_LONG.getCode())
                        );//下午有任务或全天有任务的
            }
        }
        return gcs;
    }

    /**
     * 查询空闲的领队
     *
     * @param req
     * @return
     */
    @Override
    public Result<List<GuideCollarQueryLeisureDTO>> select(GuideCollarQueryLeisureReq req) {
        QueryWrapper<GuideCollarScheduling> gcs = getQW(req);
        //得到当前这段时间有任务的人
        List<GuideCollarScheduling> guideCollarSchedulings = guideCollarSchedulingMapper.selectList(gcs);
        Set<Long> userIds = null;
        if (guideCollarSchedulings != null && guideCollarSchedulings.size() > 0) {
            userIds = guideCollarSchedulings.stream().map(e -> e.getGuideCollarId()).collect(Collectors.toSet());
        }
        QueryWrapper<GuideCollar> gc = new QueryWrapper<>();
        //领队（1）导游（2）
        gc.lambda().eq(req.getGroupType() != null, GuideCollar::getType, req.getGroupType());
        if (userIds != null) {
            //排除这个时间段忙的领队ID
            gc.lambda().notIn(GuideCollar::getId, userIds);
        }
        List<GuideCollar> guideCollars = guideCollarMapper.selectList(gc);
        List<GuideCollarQueryLeisureDTO> list = new ArrayList<>();
        for (GuideCollar guideCollar : guideCollars) {
            //这些道灵 不能是黑名单上的，不能是离职时间后在团结束时间外的
            if (guideCollar.getStatus() == GuideCollarStatus.STATUS_4.getCode()) {//黑名单
                continue;
            }
            if (guideCollar.getStatus() == GuideCollarStatus.STATUS_2.getCode()) {//离职状态 判断这次安排的任务最后回归时间是否小于离职日期
                //如果最后回归日为空说明  这是一个茶会或送团类型的任务 那么任务开始日期就是结束日期
                if (!guideCollar.getQuitDate().isAfter(req.getEndDate() == null ? req.getBeginDate().toLocalDate() : req.getEndDate().toLocalDate())) {
                    continue;
                }
            }
            GuideCollarQueryLeisureDTO copy = EntityUtil.copy(guideCollar, GuideCollarQueryLeisureDTO.class);
            list.add(copy);
        }
        return Result.success(list);
    }

    @Override
    public PageResponse<GroupDistributionListDTO> list(GroupDistributionListReq req) {
        Page<GroupDistribution> page = new Page<>();
        QueryWrapper<GroupDistribution> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(GroupDistribution::getType, req.getType())
                .eq(null != req.getStatus(), GroupDistribution::getStatus, req.getStatus())
                .eq(null != req.getGroupType(), GroupDistribution::getGroupType, req.getGroupType());
        if (null != req.getAggregateTimeBegin() && null != req.getAggregateTimeEnd()) {
            queryWrapper.lambda().between(GroupDistribution::getAggregateTime, req.getAggregateTimeBegin(), req.getAggregateTimeEnd());
        }
        if (null != req.getTotalNumberBegin() && null != req.getTotalNumberEnd()) {
            queryWrapper.lambda().between(GroupDistribution::getTotalNumber, req.getTotalNumberBegin(), req.getTotalNumberEnd());
        }
        if (null != req.getDaysBegin() && null != req.getDaysEnd()) {
            queryWrapper.lambda().between(GroupDistribution::getDays, req.getDaysBegin(), req.getDaysEnd());
        }
        queryWrapper.lambda().eq(null != req.getGroupStatus(), GroupDistribution::getGroupStatus, req.getGroupStatus())
                .like(StringUtils.isNotBlank(req.getGroupNumber()), GroupDistribution::getGroupNumber, req.getGroupNumber());
        if (req.getSortFlage() != null) {
            switch (req.getSortFlage()) {
                case 1:
                    queryWrapper.orderByAsc("aggregate_time");
                    break;
                case 2:
                    queryWrapper.orderByDesc("aggregate_time");
                    break;
                case 3:
                    queryWrapper.orderByAsc("scattered_time");
                    break;
                case 4:
                    queryWrapper.orderByDesc("scattered_time");
                    break;
            }
        }
        Page<GroupDistribution> iPage = baseMapper.selectPage(page, queryWrapper);
        List<GroupDistribution> records = iPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        getGroupDistributionInfo(records);//转换填充数据
        List<GroupDistributionListDTO> groupDistributionListDTOS = EntityUtil.copyList(records, GroupDistributionListDTO.class);
        for (GroupDistributionListDTO groupDistributionListDTO : groupDistributionListDTOS) {
            //查询全陪用户列表
            QueryWrapper<GroupDistributionFullCompany> groupDistributionFullCompanyQueryWrapper = new QueryWrapper<>();
            groupDistributionFullCompanyQueryWrapper.lambda().eq(GroupDistributionFullCompany::getDistributionId, groupDistributionListDTO.getId());
            List<GroupDistributionFullCompany> groupDistributionFullCompanies = groupDistributionFullCompanyMapper.selectList(groupDistributionFullCompanyQueryWrapper);
            List<GroupDistributionFullCompanyVO> groupDistributionFullCompanyVOS = EntityUtil.copyList(groupDistributionFullCompanies, GroupDistributionFullCompanyVO.class);
            groupDistributionListDTO.setGroupDistributionFullCompanyVOList(groupDistributionFullCompanyVOS);
            //查询送团用户列表
            QueryWrapper<GroupDistributionGiveGroup> groupDistributionGiveGroupQueryWrapper = new QueryWrapper<>();
            groupDistributionGiveGroupQueryWrapper.lambda().eq(GroupDistributionGiveGroup::getDistributionId, groupDistributionListDTO.getId());
            List<GroupDistributionGiveGroup> groupDistributionGiveGroups = groupDistributionGiveGroupMapper.selectList(groupDistributionGiveGroupQueryWrapper);
            List<GroupDistributionGiveGroupVO> groupDistributionGiveGroupVOS = EntityUtil.copyList(groupDistributionGiveGroups, GroupDistributionGiveGroupVO.class);
            groupDistributionListDTO.setGroupDistributionGiveGroupVOList(groupDistributionGiveGroupVOS);
        }
        return new PageResponse<>(groupDistributionListDTOS, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(GroupDistributionAddReq req, TokenUser tu) {
        QueryWrapper<GroupDistribution> qw = new QueryWrapper<>();
        qw.lambda().eq(GroupDistribution::getGroupId, req.getGroupId())
                .eq(GroupDistribution::getIsDeleted, IsDeletedCode.NO.getCode());
        Integer integer = baseMapper.selectCount(qw);
        if (integer > 0) {
            return Result.failed(SystemError.GUIDE_410010);
        }
        long id = IdWorker.getId();
        GroupDistribution groupDistribution = EntityUtil.copy(req, GroupDistribution.class);
        groupDistribution.setId(id);
        groupDistribution.setIsDeleted(IsDeletedCode.NO.getCode());
        groupDistribution.setStatus(GroupDistributionStatus.NO_DELEGATION.getCode());
        groupDistribution.setCreateId(tu.getId());
        groupDistribution.setGmtCreate(LocalDateTime.now());
        int insert = baseMapper.insert(groupDistribution);
        LocalDateTime begin = req.getAggregateTime();//集合时间
        LocalDateTime end = req.getScatteredTime();//散团时间
        if (insert > 0) {
            if (CollectionUtils.isNotEmpty(req.getGroupDistributionFullCompanyVOList())) {
                List<GroupDistributionFullCompany> groupDistributionFullCompanies = EntityUtil.copyList(req.getGroupDistributionFullCompanyVOList(), GroupDistributionFullCompany.class);
                for (GroupDistributionFullCompany groupDistributionFullCompany : groupDistributionFullCompanies) {
                    groupDistributionFullCompany.setDistributionId(id);
                    groupDistributionFullCompany.setId(IdWorker.getId());
                    groupDistributionFullCompanyMapper.insert(groupDistributionFullCompany);
                    //全陪 的排班任务需要从集合时间算起到散团时间整天结束
                    //上午开始的直接安排一天
                    if (begin.getHour() < 12) {
                        addGuideCollarScheduling(begin.toLocalDate(), end.toLocalDate(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarId(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.ALL_DAY_LONG.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID1,
                                GuideCollarSchedulingServiceImpl.WORKID1_NAME, tu, groupDistribution.getId());
                    } else {
                        //下午开始的安排一天半天的剩下的全部安排整天
                        addGuideCollarScheduling(begin.toLocalDate(), begin.toLocalDate(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarId(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.AFTERNOON.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID1,
                                GuideCollarSchedulingServiceImpl.WORKID1_NAME, tu, groupDistribution.getId());

                        LocalDate localDate = begin.toLocalDate().plusDays(1);//向后偏移一天
                        //开始时间是否大于结束时间
                        if (!localDate.isAfter(end.toLocalDate())) {
                            addGuideCollarScheduling(localDate, end.toLocalDate(),
                                    groupDistributionFullCompany.getFullCompanyGuideCollarId(),
                                    groupDistributionFullCompany.getFullCompanyGuideCollarName()
                                    , GuideCollarSchedulingType.DATE.getCode(),
                                    GuideCollarSchedulingWorkHours.ALL_DAY_LONG.getCode(),
                                    GuideCollarSchedulingServiceImpl.WORKID1,
                                    GuideCollarSchedulingServiceImpl.WORKID1_NAME, tu, groupDistribution.getId());
                        }
                    }
                }
            }
            if (CollectionUtils.isNotEmpty(req.getGroupDistributionGiveGroupVOList())) {
                List<GroupDistributionGiveGroup> GroupDistributionGiveGroups = EntityUtil.copyList(req.getGroupDistributionGiveGroupVOList(), GroupDistributionGiveGroup.class);
                for (GroupDistributionGiveGroup groupDistributionGiveGroup : GroupDistributionGiveGroups) {
                    groupDistributionGiveGroup.setDistributionId(id);
                    groupDistributionGiveGroup.setId(IdWorker.getId());
                    groupDistributionGiveGroupMapper.insert(groupDistributionGiveGroup);
                    //送团的
                    if (begin.getHour() < 12) {
                        addGuideCollarScheduling(begin.toLocalDate(), begin.toLocalDate(),
                                groupDistributionGiveGroup.getGiveGroupGuideCollarId(),
                                groupDistributionGiveGroup.getGiveGroupGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.FORENOON.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID2,
                                GuideCollarSchedulingServiceImpl.WORKID2_NAME, tu, groupDistribution.getId());
                    } else {
                        addGuideCollarScheduling(begin.toLocalDate(), begin.toLocalDate(),
                                groupDistributionGiveGroup.getGiveGroupGuideCollarId(),
                                groupDistributionGiveGroup.getGiveGroupGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.AFTERNOON.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID2,
                                GuideCollarSchedulingServiceImpl.WORKID2_NAME, tu, groupDistribution.getId());
                    }
                }
            }
        }
        return Result.success(id);
    }

    private void addGuideCollarScheduling(LocalDate begin, LocalDate end, Long guideCollarId,
                                          String guideCollarName, Integer type, Integer hours
            , Long workTypeId, String workTypeName, TokenUser tu, Long groupId) {
        GuideCollarSchedulingAddReq gcslareq = new GuideCollarSchedulingAddReq();
        gcslareq.setSchedulingDateBegin(begin);//安排开始日期
        gcslareq.setSchedulingDateEnd(end);//安排终止日期
        gcslareq.setGuideCollarId(guideCollarId);//导领ID
        gcslareq.setGuideCollarName(guideCollarName);//导领名称
        gcslareq.setArrangementType(type);//安排类型
        gcslareq.setWorkingHours(hours);//工作时段
        gcslareq.setWorkTypeId(workTypeId);//工作类型id
        gcslareq.setWorkTypeName(workTypeName);//工作类型name
        gcslareq.setGroupId(groupId);//这里是派团团详情ID
        guideCollarSchedulingService.add(gcslareq, tu, false);
    }

    @Override
    public GroupDistributionListDTO query(GroupDistributionIdReq req) {
        GroupDistribution groupDistribution = baseMapper.selectById(req.getId());
        if (groupDistribution != null) {
            List<GroupDistribution> gds = new ArrayList<>();
            gds.add(groupDistribution);
            getGroupDistributionInfo(gds);//转换填充数据
            GroupDistributionListDTO groupDistributionListDTO = EntityUtil.copy(groupDistribution, GroupDistributionListDTO.class);
            if (null != groupDistributionListDTO.getFullCompanyCertificatesId()) {
                MainDataFieldDataDTO mainDataFieldDataDTO = mainDataFieldDataService.queryFieldData(groupDistributionListDTO.getFullCompanyCertificatesId());
                groupDistributionListDTO.setFullCompanyCertificatesName(mainDataFieldDataDTO.getFieldValue());
            }
            if (null != groupDistributionListDTO.getGiveGroupCertificatesId()) {
                MainDataFieldDataDTO mainDataFieldDataDTO = mainDataFieldDataService.queryFieldData(groupDistributionListDTO.getGiveGroupCertificatesId());
                groupDistributionListDTO.setGiveGroupCertificatesName(mainDataFieldDataDTO.getFieldValue());
            }
            //查询全陪用户列表
            QueryWrapper<GroupDistributionFullCompany> groupDistributionFullCompanyQueryWrapper = new QueryWrapper<>();
            groupDistributionFullCompanyQueryWrapper.lambda().eq(GroupDistributionFullCompany::getDistributionId, groupDistribution.getId());
            List<GroupDistributionFullCompany> groupDistributionFullCompanies = groupDistributionFullCompanyMapper.selectList(groupDistributionFullCompanyQueryWrapper);
            List<GroupDistributionFullCompanyVO> groupDistributionFullCompanyVOS = EntityUtil.copyList(groupDistributionFullCompanies, GroupDistributionFullCompanyVO.class);
            groupDistributionListDTO.setGroupDistributionFullCompanyVOList(groupDistributionFullCompanyVOS);
            //查询送团用户列表
            QueryWrapper<GroupDistributionGiveGroup> groupDistributionGiveGroupQueryWrapper = new QueryWrapper<>();
            groupDistributionGiveGroupQueryWrapper.lambda().eq(GroupDistributionGiveGroup::getDistributionId, groupDistribution.getId());
            List<GroupDistributionGiveGroup> groupDistributionGiveGroups = groupDistributionGiveGroupMapper.selectList(groupDistributionGiveGroupQueryWrapper);
            List<GroupDistributionGiveGroupVO> groupDistributionGiveGroupVOS = EntityUtil.copyList(groupDistributionGiveGroups, GroupDistributionGiveGroupVO.class);
            groupDistributionListDTO.setGroupDistributionGiveGroupVOList(groupDistributionGiveGroupVOS);
            return groupDistributionListDTO;
        }
        return null;
    }

    @Override
    public Result<GroupInfoDTO> queryById(Long id) {
        QueryWrapper<GroupDistribution> qwgd = new QueryWrapper<>();
        qwgd.lambda().select(GroupDistribution::getId)
                .eq(GroupDistribution::getIsDeleted,IsDeletedCode.NO.getCode())
                .eq(GroupDistribution::getGroupId,id);
        //依据团期ID查询团详情
        GroupDistribution gd = baseMapper.selectOne(qwgd);
        GroupInfoDTO result = new GroupInfoDTO();
        if(gd != null){
            QueryWrapper<GuideCollar> qw = new QueryWrapper<>();
            QueryWrapper<GroupDistributionFullCompany> gdfc = new QueryWrapper<>();
            gdfc.lambda().select(GroupDistributionFullCompany::getFullCompanyGuideCollarId)
                    .eq(GroupDistributionFullCompany::getIsDeleted, IsDeletedCode.NO.getCode())
                    .eq(GroupDistributionFullCompany::getDistributionId, gd.getId());
            List<GroupDistributionFullCompany> gdfcs = groupDistributionFullCompanyMapper.selectList(gdfc);
            List<Long> gdfcsIds = gdfcs.stream().map(e -> e.getFullCompanyGuideCollarId()).collect(Collectors.toList());
            if (gdfcsIds != null && gdfcsIds.size() > 0) {//全陪用户
                qw.lambda().select(GuideCollar::getCnSurname, GuideCollar::getCnName)
                        .eq(GuideCollar::getId, gdfcsIds)
                        .eq(GuideCollar::getIsDeleted, IsDeletedCode.NO.getCode());
                List<GuideCollar> guideCollars = guideCollarMapper.selectList(qw);
                if (guideCollars != null && guideCollars.size() > 0) {
                    String name = "";
                    for (int i = 0; i < guideCollars.size(); i++) {
                        name = guideCollars.get(i).getCnSurname() + guideCollars.get(i).getCnName();
                        String fix = i == guideCollars.size() - 1 ? "" : "/";
                        name += fix;
                    }
                    result.setGuideName(name);
                }
            }
            QueryWrapper<GroupDistributionGiveGroup> gdgg = new QueryWrapper<>();
            gdgg.lambda().select(GroupDistributionGiveGroup::getGiveGroupGuideCollarId)
                    .eq(GroupDistributionGiveGroup::getIsDeleted, IsDeletedCode.NO.getCode())
                    .eq(GroupDistributionGiveGroup::getDistributionId, id);
            List<GroupDistributionGiveGroup> gdggs = groupDistributionGiveGroupMapper.selectList(gdgg);
            List<Long> gdggsIds = gdggs.stream().map(e -> e.getGiveGroupGuideCollarId()).collect(Collectors.toList());
            if (gdggsIds != null && gdggsIds.size() > 0) {//送团用户
                qw.clear();//清除条件
                qw.lambda().select(GuideCollar::getCnSurname, GuideCollar::getCnName)
                        .eq(GuideCollar::getId, gdggsIds)
                        .eq(GuideCollar::getIsDeleted, IsDeletedCode.NO.getCode());
                List<GuideCollar> guideCollars = guideCollarMapper.selectList(qw);
                if (guideCollars != null && guideCollars.size() > 0) {
                    String name = "";
                    for (int i = 0; i < guideCollars.size(); i++) {
                        name = guideCollars.get(i).getCnSurname() + guideCollars.get(i).getCnName();
                        String fix = i == guideCollars.size() - 1 ? "" : "/";
                        name += fix;
                    }
                    result.setSendBackName(name);
                }
            }
            QueryWrapper<TeaParty> tp = new QueryWrapper<>();
            tp.lambda().eq(TeaParty::getIsDeleted, IsDeletedCode.NO.getCode())
                    .eq(TeaParty::getGroupId, id);
            List<TeaParty> teaParties = teaPartyMapper.selectList(tp);
            if (teaParties != null && teaParties.size() > 0) {
                List<TeaPartyDTO> tpd = EntityUtil.copyList(teaParties, TeaPartyDTO.class);
                if (tpd != null && tpd.size() > 0) {
                    if(tpd.get(0) != null){
                        result.setTeaAddreass(tpd.get(0).getTeaPartyAreaName());
                        result.setTeaPartyHost(tpd.get(0).getTeaPartyHost());
                        result.setTeaPartyRoom(tpd.get(0).getTeaPartyRoom());
                        result.setTeaPartyTime(tpd.get(0).getTeaPartyTime());
                    }
                }
            }
        }
        return Result.success(result);
    }

    /**
     * 查询数据填充
     *
     * @param gds
     */
    private void getGroupDistributionInfo(List<GroupDistribution> gds) {
        List<Long> lxtIds = new ArrayList<>();
        List<Long> dzbtIds = new ArrayList<>();
        Map<Long, TripScheduleGuideDTO> map = new HashMap<>();
        Map<Long, com.ctshk.rpc.tour.dto.schedule.TripScheduleGuideDTO> map2 = new HashMap<>();
        //这个地方由于弃用所有关于团的数据库信息，改用实施查询定制抱团，和团期详情的信息
        for (GroupDistribution e : gds) {
            if(e!=null){
                //旅行团
                if (GroupDistributionGroupType.GROUP.getCode().equals(e.getGroupType())) {
                    lxtIds.add(e.getGroupId());
                } else {
                    dzbtIds.add(e.getGroupId());
                }
            }
        }
        //转换旅行团的信息
        if (lxtIds.size() > 0) {
            try {
                List<com.ctshk.rpc.tour.dto.schedule.TripScheduleGuideDTO> scheduleList1 = null;
                try{
                    scheduleList1 = seriesTripScheduleService.getScheduleList(lxtIds);
                }catch (Exception ex){
                    log.error("导领中心：调用查询旅行团的详细信息，服务调用失败,错误的信息："+ex.getMessage());
                }
                for (com.ctshk.rpc.tour.dto.schedule.TripScheduleGuideDTO item : scheduleList1) {
                    map2.put(item.getId(), item);
                }
                for (GroupDistribution e : gds) {
                    com.ctshk.rpc.tour.dto.schedule.TripScheduleGuideDTO tsg = map2.get(e.getGroupId());
                    if (tsg != null) {
                        e.setDays(tsg.getTravelDays());//天数
                        if (!GroupDistributionGroupStatus.GROUP_STATUS_9.getCode().equals(e.getGroupStatus())) {
                            //转换为综合枚举类型 团队状态(1:未成团 2：已成团 3：停售 4：保留 5：不成团 6：已完团)
                            switch (tsg.getGroupStatus()) {
                                case 1:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_1.getCode());
                                    break;
                                case 2:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_2.getCode());
                                    break;
                                case 3:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_4.getCode());
                                    break;
                                case 4:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_6.getCode());
                                    break;
                                case 5:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_7.getCode());
                                    break;
                                case 6:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_8.getCode());
                                    break;
                            }
                        }
                        e.setIsTips(tsg.getNeedTripConsumption());//小费
                        e.setRequirement(tsg.getGuideRequirement());//导领要求
                        e.setCollectionPlaceAreaName(tsg.getCollectionPlace());//集合地点名称
                        e.setTotalNumber(tsg.getTotalPeople());//团期总人数
                        e.setReceivedNumber(tsg.getOrderPeople());//收纳人数（下单人数）
                    }
                }
            }catch (Exception e){
                log.error("导领中心：转换团期管理信息失败，错误的信息："+e.getMessage());
            }
        }
        //转换团期管理的信息
        if (dzbtIds.size() > 0) {
            try{
                List<TripScheduleGuideDTO> scheduleList = null;
                try{
                    scheduleList = customizedTripScheduleService.getScheduleList(dzbtIds);
                }catch (Exception ex){
                    log.error("导领中心：调用查询到团期管理的详细信息，服务调用失败,错误的信息："+ex.getMessage());
                }
                if (scheduleList == null || scheduleList.size() < 1){
                    log.error("导领中心：没有查询到团期管理的详细信息，请查看团期管理数据是否对应！");
                }
                for (TripScheduleGuideDTO item : scheduleList) {
                    map.put(item.getId(), item);
                }
                for (GroupDistribution e : gds) {
                    TripScheduleGuideDTO tsg = map.get(e.getGroupId());
                    if (tsg != null) {
                        e.setDays(tsg.getTravelDays());//天数
                        if (e.getGroupStatus() != GroupDistributionGroupStatus.GROUP_STATUS_9.getCode()) {
                            //转换为综合枚举类型 团队状态(1 开售 2 不成团 3 已成团 4 已完团 5 已保存)
                            switch (tsg.getGroupStatus()) {
                                case 1:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_3.getCode());
                                    break;
                                case 2:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_7.getCode());
                                    break;
                                case 3:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_2.getCode());
                                    break;
                                case 4:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_8.getCode());
                                    break;
                                case 5:
                                    e.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_5.getCode());
                                    break;
                            }
                        }
                        e.setIsTips(tsg.getNeedTripConsumption());//小费
                        e.setRequirement(tsg.getGuideRequirement());//导领要求
                        e.setCollectionPlaceAreaName(tsg.getCollectionPlace());//集合地点名称
                        e.setTotalNumber(tsg.getTotalPeople());//团期总人数
                        e.setReceivedNumber(tsg.getOrderPeople());//收纳人数（下单人数）
                    }
                }
            }catch (Exception e){
                log.error("导领中心：转换团期管理信息失败，错误的信息："+e.getMessage());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result update(GroupDistributionUpdateReq req, TokenUser tu) {
        //通过主键Id修改派团信息(全陪/送团人员/团状态/收客数/状态）
        if (req.getId() == null) {
            return Result.failed(SystemError.GUIDE_41006);
        }
        GroupDistribution gd = baseMapper.selectById(req.getId());
        LocalDateTime begin = req.getAggregateTime();//集合时间
        LocalDateTime end = req.getScatteredTime();//散团时间
        Long id = req.getId();
        if (req.getStatus() == GuideCollarType.NATIONAL_GUIDE.getCode()) {
            if (CollectionUtils.isNotEmpty(req.getGroupDistributionFullCompanyVOList())) {
                //派团以后修改状态
                gd.setStatus(GroupDistributionStatus.YES_DELEGATION.getCode());
                //判断导领有无合约到期
                for (GroupDistributionFullCompanyVO e : req.getGroupDistributionFullCompanyVOList()) {
                    GuideCollar gc = guideCollarMapper.selectById(e.getFullCompanyGuideCollarId());
                    if (gc != null) {
                        int workDays = Period.between(gc.getEntryTime(), LocalDate.now()).getDays();
                        if (workDays > gc.getContractPeriod() * 365) {
                            return Result.failed(SystemError.GUIDE_410011);
                        }
                    } else {
                        return Result.failed(SystemError.GUIDE_41005);
                    }
                }
                ;
                //查询到要安排的导领
                List<Long> gcIds = req.getGroupDistributionFullCompanyVOList().stream().map(e -> e.getFullCompanyGuideCollarId()).collect(Collectors.toList());
                QueryWrapper<GuideCollar> qwgc = new QueryWrapper<>();
                qwgc.lambda().in(GuideCollar::getId, gcIds)
                        .eq(GuideCollar::getIsDeleted, IsDeletedCode.NO.getCode())
                        .eq(req.getType() != null, GuideCollar::getType, req.getType())
                        .and(e ->
                                e.eq(GuideCollar::getCertificatesStatus, GroupCollarCertificatesStatus.CERTIFICATE_STATUS_1.getCode())
                                        .or().eq(GuideCollar::getCertificatesStatus, GroupCollarCertificatesStatus.CERTIFICATE_STATUS_2.getCode())
                        );
                List<GuideCollar> guideCollars = guideCollarMapper.selectList(qwgc);
                //有证件失效的领队 操作失败失败
                if (guideCollars == null || gcIds.size() != guideCollars.size()) {
                    return Result.failed(SystemError.GUIDE_41007);
                } else {
                    //存储领队证件IDs

                    List<GuideCollarCertificates> gcc = guideCollarCertificatesMapper.selectList(Wrappers.<GuideCollarCertificates>lambdaQuery().in(GuideCollarCertificates::getGuideCollarId, gcIds));
                    if (gcc != null && gcc.size() > 0) {
                        List<Long> collect = gcc.stream().map(e -> e.getId()).collect(Collectors.toList());
                        gd.setFullCompanyCertificates(collect);//存储拥有的证件集合
                    } else {
                        return Result.failed(SystemError.GUIDE_41007);
                    }
                }
                //todo 判断要安排的领队这个时间段是否空闲（如果安排的是当前团详情那么就不判断了）
                List<GroupDistributionFullCompanyVO> tphs = req.getGroupDistributionFullCompanyVOList();
                // 校监全陪用户有无工作安排   如果要安排的全陪用户的 原工作安排  就是当前这个团信息  就不需要判断跳过就行了
                if (tphs != null && tphs.size() > 0) {
                    GuideCollarQueryLeisureReq gcqlreq = new GuideCollarQueryLeisureReq();
                    gcqlreq.setBeginDate(gd.getAggregateTime());//集合时间
                    gcqlreq.setEndDate(gd.getScatteredTime());//散团时间
                    gcqlreq.setType(GuideCollarType.NATIONAL_GUIDE.getCode());
//                gcqlreq.setGroupType(1);//是否需要筛选领队或导游
                    Result<List<GuideCollarQueryLeisureDTO>> select = select(gcqlreq);
                    //这段时间和全天的所有的任务这些任务包含
                    List<GuideCollarSchedulingDTO> task = getTask(gcqlreq);
                    List<Long> userIds = null;
                    if (task != null && task.size() > 0) {
                        //过滤这些任务取出和当前团详情有关系的任务
                        task = task.stream().filter(e -> e.getGroupId() == gd.getId()).collect(Collectors.toList());
                        if (task != null && task.size() > 0) {
                            //得到为当前团详情服务的领队或导领IDS
                            userIds = task.stream().map(e -> e.getGuideCollarId()).collect(Collectors.toList());
                        }
                    }
                    List<GuideCollarQueryLeisureDTO> data = select.getData();
                    if (data == null || data.size() < 1) {
                        return Result.failed(SystemError.GUIDE_41008);
                    }
                    //空闲的领队或导游
                    Set<Long> collect1 = data.stream().map(e -> e.getId()).collect(Collectors.toSet());
                    //想安排的领队或导游
                    Set<Long> collect2 = tphs.stream().map(e -> e.getFullCompanyGuideCollarId()).collect(Collectors.toSet());
                    for (Long item : collect2) {
                        //要安排的领队必须在空闲领队中出现 否则就失败
                        if (!collect1.contains(item)) {
                            //想安排的领队或导游原本就是服务这个团信息的不算
                            if (userIds != null && userIds.contains(item)) {
                                continue;
                            }
                            return Result.failed(SystemError.GUIDE_41008);
                        }
                    }
                }
                //查出所有的负责这个团的道领ID
                List<GroupDistributionFullCompany> gdfc = groupDistributionFullCompanyMapper.selectList(new QueryWrapper<GroupDistributionFullCompany>().lambda().eq(GroupDistributionFullCompany::getDistributionId, id));
                Set<Long> collect = gdfc.stream().map(e -> e.getFullCompanyGuideCollarId()).collect(Collectors.toSet());
                if (collect != null && collect.size() > 0) {
                    //需要删除这些人在这个团集合山团时间内的排班任务然后从新添加
                    if (begin.getHour() < 12) { //上午说明没有半天的
                        deleteScheduling(collect, gd.getId(), begin.toLocalDate(), end.toLocalDate(), null, null);
                    } else {//下午说明有半天的
                        //删除最前面那个半天
                        deleteScheduling(collect, gd.getId(), begin.toLocalDate(), end.toLocalDate(), GuideCollarSchedulingWorkHours.AFTERNOON.getCode(), null);
                        //删除后面那些(需要向前偏移一天)
                        deleteScheduling(collect, gd.getId(), begin.toLocalDate().plusDays(1), end.toLocalDate(), null, null);
                    }
                    //删除原因的全陪道灵
                    groupDistributionFullCompanyMapper.delete(new QueryWrapper<GroupDistributionFullCompany>().lambda().eq(GroupDistributionFullCompany::getDistributionId, id));
                }
                List<GroupDistributionFullCompany> groupDistributionFullCompanies = EntityUtil.copyList(req.getGroupDistributionFullCompanyVOList(), GroupDistributionFullCompany.class);
                for (GroupDistributionFullCompany groupDistributionFullCompany : groupDistributionFullCompanies) {
                    //循环新增新的全陪道灵
                    groupDistributionFullCompany.setDistributionId(id);
                    groupDistributionFullCompany.setId(IdWorker.getId());
                    groupDistributionFullCompanyMapper.insert(groupDistributionFullCompany);
                    //如果修改了全陪（在上面已经提前删除了这些人的排版记录，现在从新安排新人员的排班记录）
                    if (begin.getHour() < 12) { //上午说明没有半天的
                        addGuideCollarScheduling(begin.toLocalDate(), end.toLocalDate(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarId(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.ALL_DAY_LONG.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID1,
                                GuideCollarSchedulingServiceImpl.WORKID1_NAME, tu, gd.getId());
                    } else {//有半天的
                        //添加一天下午的半天的排班安排
                        addGuideCollarScheduling(begin.toLocalDate(), begin.toLocalDate(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarId(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.AFTERNOON.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID1,
                                GuideCollarSchedulingServiceImpl.WORKID1_NAME, tu, gd.getId());
                        //添加整天的排班记录 往后推一天
                        addGuideCollarScheduling(begin.toLocalDate().plusDays(1), end.toLocalDate(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarId(),
                                groupDistributionFullCompany.getFullCompanyGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.ALL_DAY_LONG.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID1,
                                GuideCollarSchedulingServiceImpl.WORKID1_NAME, tu, gd.getId());
                    }

                }
            } else {
                //那就要清除这个团详情的全陪的工作安排
                deleteScheduling(null, gd.getId(), null, null, null, GuideCollarSchedulingServiceImpl.WORKID1);
                //删除这个团详情的所有全陪导领和团详情的关系
                groupDistributionFullCompanyMapper.delete(new QueryWrapper<GroupDistributionFullCompany>().lambda().eq(GroupDistributionFullCompany::getDistributionId, id));
            }
        } else if (req.getStatus() == GuideCollarType.SEND_GROUP.getCode()) {
            if (CollectionUtils.isNotEmpty(req.getGroupDistributionGiveGroupVOList())) {
                //派团以后修改状态
                gd.setStatus(GroupDistributionStatus.YES_DELEGATION.getCode());
                //判断导领有无合约到期
                for (GroupDistributionGiveGroupVO e : req.getGroupDistributionGiveGroupVOList()) {
                    GuideCollar gc = guideCollarMapper.selectById(e.getGiveGroupGuideCollarId());
                    if (gc != null) {
                        int workDays = Period.between(gc.getEntryTime(), LocalDate.now()).getDays();
                        if (workDays > gc.getContractPeriod() * 365) {
                            return Result.failed(SystemError.GUIDE_410011);
                        }
                    } else {
                        return Result.failed(SystemError.GUIDE_41005);
                    }
                }
                ;
                //查询到要安排的导领
                List<Long> gcIds = req.getGroupDistributionGiveGroupVOList().stream().map(e -> e.getGiveGroupGuideCollarId()).collect(Collectors.toList());
                QueryWrapper<GuideCollar> qwgc = new QueryWrapper<>();
                qwgc.lambda().in(GuideCollar::getId, gcIds)
                        .eq(GuideCollar::getIsDeleted, IsDeletedCode.NO.getCode())
                        .eq(req.getType() != null, GuideCollar::getType, req.getType());
                List<GuideCollar> guideCollars = guideCollarMapper.selectList(qwgc);
                //有证件失效的领队 操作失败
                if (guideCollars == null || gcIds.size() != guideCollars.size()) {
                    return Result.failed(SystemError.GUIDE_41007);
                } else {
                    //存储领队证件IDs
                    List<GuideCollarCertificates> gcc = guideCollarCertificatesMapper.selectList(Wrappers.<GuideCollarCertificates>lambdaQuery().in(GuideCollarCertificates::getGuideCollarId, gcIds));
                    if (gcc != null && gcc.size() > 0) {
                        List<Long> collect = gcc.stream().map(e -> e.getId()).collect(Collectors.toList());
                        gd.setGiveGroupCertificates(collect);
                    } else {
                        return Result.failed(SystemError.GUIDE_41007);
                    }
                }
                //todo 判断要安排的领队这个时间段是否空闲（如果安排的是当前团详情那么就不判断了）
                List<GroupDistributionGiveGroupVO> tphs = req.getGroupDistributionGiveGroupVOList();
                // 校监送团用户有无工作安排   如果要安排的送团用户的 原工作安排  就是当前这个团信息  就不需要判断跳过就行了
                if (tphs != null && tphs.size() > 0) {
                    GuideCollarQueryLeisureReq gcqlreq = new GuideCollarQueryLeisureReq();
                    gcqlreq.setBeginDate(gd.getAggregateTime());//集合时间
                    gcqlreq.setType(GuideCollarType.SEND_GROUP.getCode());
//                gcqlreq.setGroupType(1);//是否需要筛选领队或导游
                    Result<List<GuideCollarQueryLeisureDTO>> select = select(gcqlreq);
                    //这段时间和全天的所有的任务这些任务包含
                    List<GuideCollarSchedulingDTO> task = getTask(gcqlreq);
                    List<Long> userIds = null;
                    if (task != null && task.size() > 0) {
                        //过滤这些任务取出和当前团详情有关系的任务
                        task = task.stream().filter(e -> e.getGroupId() == gd.getId()).collect(Collectors.toList());
                        if (task != null && task.size() > 0) {
                            //得到为当前团详情服务的领队或导领IDS
                            userIds = task.stream().map(e -> e.getGuideCollarId()).collect(Collectors.toList());
                        }
                    }
                    List<GuideCollarQueryLeisureDTO> data = select.getData();
                    if (data == null || data.size() < 1) {
                        return Result.failed(SystemError.GUIDE_41008);
                    }
                    //空闲的领队或导游
                    Set<Long> collect1 = data.stream().map(e -> e.getId()).collect(Collectors.toSet());
                    //想安排的领队或导游
                    Set<Long> collect2 = tphs.stream().map(e -> e.getGiveGroupGuideCollarId()).collect(Collectors.toSet());
                    for (Long item : collect2) {
                        //要安排的领队必须在空闲领队中出现 否则就失败
                        if (!collect1.contains(item)) {
                            //想安排的领队或导游原本就是服务这个团信息的不算
                            if (userIds != null && userIds.contains(item)) {
                                continue;
                            }
                            return Result.failed(SystemError.GUIDE_41008);
                        }
                    }
                }
                //查出所有的负责这个团的道领ID
                List<GroupDistributionGiveGroup> gdfc = groupDistributionGiveGroupMapper.selectList(new QueryWrapper<GroupDistributionGiveGroup>().lambda().eq(GroupDistributionGiveGroup::getDistributionId, id));
                Set<Long> collect = gdfc.stream().map(e -> e.getGiveGroupGuideCollarId()).collect(Collectors.toSet());
                if (collect != null && collect.size() > 0) {
                    //如果集合时间是上午那么送团的就只有当天上午有一个任务安排反之则是下午（删除它从新添加）
                    if (begin.getHour() < 12) { //上午
                        //删除送团的上午任务
                        QueryWrapper<GuideCollarScheduling> qw = new QueryWrapper();
                        qw.lambda().eq(GuideCollarScheduling::getSchedulingDate, begin.toLocalDate())
                                .eq(GuideCollarScheduling::getWorkingHours, GuideCollarSchedulingWorkHours.FORENOON.getCode())//（只删除上午的）
                                .eq(GuideCollarScheduling::getGroupId, gd.getId())//匹配是同一个团信息的工作安排
                                .in(GuideCollarScheduling::getGuideCollarId, collect);
                        guideCollarSchedulingMapper.delete(qw);
                        deleteScheduling(collect, gd.getId(), begin.toLocalDate().plusDays(1), end.toLocalDate(), null, null);
                    } else {//下午
                        //删除送团的下午任务
                        QueryWrapper<GuideCollarScheduling> qw = new QueryWrapper();
                        qw.lambda().eq(GuideCollarScheduling::getSchedulingDate, begin.toLocalDate())
                                .eq(GuideCollarScheduling::getWorkingHours, GuideCollarSchedulingWorkHours.AFTERNOON.getCode())//（只删除下午的）
                                .eq(GuideCollarScheduling::getGroupId, gd.getId())//匹配是同一个团信息的工作安排
                                .in(GuideCollarScheduling::getGuideCollarId, collect);
                        guideCollarSchedulingMapper.delete(qw);
                    }
                    //删除送团的道灵记录
                    groupDistributionGiveGroupMapper.delete(new QueryWrapper<GroupDistributionGiveGroup>().lambda().eq(GroupDistributionGiveGroup::getDistributionId, id));
                }
                List<GroupDistributionGiveGroup> GroupDistributionGiveGroups = EntityUtil.copyList(req.getGroupDistributionGiveGroupVOList(), GroupDistributionGiveGroup.class);
                for (GroupDistributionGiveGroup groupDistributionGiveGroup : GroupDistributionGiveGroups) {
                    groupDistributionGiveGroup.setDistributionId(id);
                    groupDistributionGiveGroup.setId(IdWorker.getId());
                    groupDistributionGiveGroupMapper.insert(groupDistributionGiveGroup);
                    //上面删除了送团的道灵用户 就需要把新的道灵任务给排上
                    if (begin.getHour() < 12) { //上午新增一个半天任务
                        addGuideCollarScheduling(begin.toLocalDate(), begin.toLocalDate(),
                                groupDistributionGiveGroup.getGiveGroupGuideCollarId(),
                                groupDistributionGiveGroup.getGiveGroupGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.FORENOON.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID2,
                                GuideCollarSchedulingServiceImpl.WORKID2_NAME, tu, gd.getId());
                    } else {//下午新增一个半天任务
                        addGuideCollarScheduling(begin.toLocalDate(), begin.toLocalDate(),
                                groupDistributionGiveGroup.getGiveGroupGuideCollarId(),
                                groupDistributionGiveGroup.getGiveGroupGuideCollarName()
                                , GuideCollarSchedulingType.DATE.getCode(),
                                GuideCollarSchedulingWorkHours.AFTERNOON.getCode(),
                                GuideCollarSchedulingServiceImpl.WORKID2,
                                GuideCollarSchedulingServiceImpl.WORKID2_NAME, tu, gd.getId());
                    }
                }
            } else {
                //那就要清除这个团详情的送团工作安排
                deleteScheduling(null, gd.getId(), null, null, null, GuideCollarSchedulingServiceImpl.WORKID2);
                //删除这个团详情的 送团导领和团详情关系
                groupDistributionGiveGroupMapper.delete(new QueryWrapper<GroupDistributionGiveGroup>().lambda().eq(GroupDistributionGiveGroup::getDistributionId, id));
            }
        }
        baseMapper.updateById(gd);
        return Result.success();
    }

    @Override
    public Result updateTime(GroupDistributionIdUpdateStatusReq req, Long userId) {
        QueryWrapper<GroupDistribution> qw = new QueryWrapper();
        qw.lambda().eq(GroupDistribution::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(GroupDistribution::getGroupType, req.getGroupType())
                .eq(GroupDistribution::getGroupId, req.getGroupId());
        GroupDistribution gd = baseMapper.selectOne(qw);
        if (gd != null) {
            //团期或旅行团修改了集合时间和散团时间，状态修改为9提示用户重新排班
            gd.setGroupStatus(GroupDistributionGroupStatus.GROUP_STATUS_9.getCode());
            gd.setAggregateTime(req.getBeginTime());
            gd.setScatteredTime(req.getEndTime());
            gd.setModifiedId(userId);
            gd.setGmtModified(LocalDateTime.now());
            UpdateWrapper<GroupDistribution> uw = new UpdateWrapper<>();
            int update = baseMapper.update(gd, uw);
            return Result.success(update);
        }
        return Result.failed(SystemError.GUIDE_410012);
    }

    /**
     * 删除工作安排
     *
     * @param userIds 导领或领队的IDS
     * @param groupId 团详情ID
     * @param begin   集合时间
     * @param end     散团时间
     * @return
     */
    private int deleteScheduling(Set<Long> userIds, Long groupId, LocalDate begin, LocalDate end, Integer wh, Long wt) {
        QueryWrapper<GuideCollarScheduling> qw = new QueryWrapper();
        qw.lambda().ge(begin != null, GuideCollarScheduling::getSchedulingDate, begin)
                .eq(wh != null, GuideCollarScheduling::getWorkingHours, wh)
                .eq(wt != null, GuideCollarScheduling::getWorkTypeId, wt)
                .le(end != null, GuideCollarScheduling::getSchedulingDate, end)
                .eq(GuideCollarScheduling::getGroupId, groupId)//匹配是同一个团信息的工作安排
                .in(userIds != null, GuideCollarScheduling::getGuideCollarId, userIds);
        return guideCollarSchedulingMapper.delete(qw);
    }

}
